package com.yanqu.road.server.manager.douluodalu.impl;

import com.yanqu.road.entity.activity.douluodalu.DouLuoDaLuUserEvent;
import com.yanqu.road.entity.activity.douluodalu.config.DouLuoDaLuEventInfo;
import com.yanqu.road.entity.activity.douluodalu.config.DouLuoDaLuRegionInfo;
import com.yanqu.road.entity.activity.douluodalu.data.DouLuoDaLuHelpRecordData;
import com.yanqu.road.entity.activity.douluodalu.data.DouLuoDaLuUserData;
import com.yanqu.road.entity.activity.douluodalu.log.DouLuoDaLuEventNoticeData;
import com.yanqu.road.entity.log.cross.LogDouLuoDaLuHunHuan;
import com.yanqu.road.entity.log.cross.LogDouLuoDaLuKill;
import com.yanqu.road.server.manager.douluodalu.*;
import com.yanqu.road.server.manager.log.CrossAutoLogMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.mina.util.ConcurrentHashSet;

import java.util.Map;
import java.util.Set;

/**
 * 真人事件
 */
public class DouLuoDaLuPlayerFightEventAction extends DouLuoDaLuBaseFightEventAction implements IDouLuoDaLuUserEventAction {


    public DouLuoDaLuPlayerFightEventAction(CrossDouLuoDaLuContext context, DouLuoDaLuEventInfo eventInfo) {
        super(context, eventInfo);
    }

    @Override
    DouLuoDaLuEventResult init0() {
        DouLuoDaLuEventResult eventResult = new DouLuoDaLuEventResult();
        //随机同区域的真人玩家
        DouLuoDaLuUserData enemyUserData = context.getActivity().randomRegionPlayer(context.getUserData(), context.getTeamData());
        if(enemyUserData == null){
            eventResult.setRet(-1);
            return eventResult;
        }
        DouLuoDaLuUserEvent event = new DouLuoDaLuUserEvent();
        event.setTotalBlood(enemyUserData.getTotalBlood());
        event.setBlood(enemyUserData.getBlood());
        event.setEventId(eventInfo.getEventId());
        event.setEventType(eventInfo.getEventType());
        event.setMonsterId(0);
        event.setEnemyUserId(enemyUserData.getUserId());
        event.setRegionId(context.getUserData().getRegionId());
        event.setAddTime(DateHelper.getCurrentSecond());
        context.getUserData().setEvent(event);
        eventResult.setUserEvent(event);

        enemyUserData.getCanAttackUserSet().add(context.getUserData());
        return eventResult;
    }

    /**
     * @param action 1:攻击；2：标记；3：绕过
     */
    @Override
    DouLuoEventHandleResult handle0(int action, byte[] params) {
        DouLuoEventHandleResult handleResult = super.handle0(action, params);
        if(handleResult.getRet() != 0){
            return handleResult;
        }

        DouLuoDaLuUserData userData = context.getUserData();
        DouLuoDaLuUserEvent event = userData.getEvent();
        handleResult.setUserEvent(event);

        DouLuoDaLuUserData enemyUserData = context.getActivity().getAllUserMap().get(event.getEnemyUserId());
        if(enemyUserData == null){
            handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_PLAYER_NOT_IN_REGION);
            return handleResult;
        }

        DouLuoDaLuRegionInfo regionInfo = context.getActivity().getConfig().getRegionInfo(event.getRegionId());

        if(action == 1){
            //缓存总血量
            long totalBlood;
            //抢的魂环奖励
            Property hunHuanProperty = new Property();
            //道具奖励
            Property goodsProperty = new Property();
            //对手身上师傅掉落魂环
            boolean enemyLost = false;
            //标志对手的所有玩家
            Set<DouLuoDaLuUserData> markEnemySet;
            int oldRegionId;
            DouLuoDaLuRegionInfo preRegionInfo;
            long now;
            int attackTime;
            //以玩家身上的数据为主数据
            DouLuoDaLuHelpRecordData helpRecordData;

            now = System.currentTimeMillis();
            attackTime = DateHelper.getCurrentSecond();
            oldRegionId = enemyUserData.getRegionId();
            preRegionInfo = context.getActivity().getConfig().getPreRegionInfo(oldRegionId);
            DouLuoDaLuHelpRecordData recordData = userData.getCurrentHelpRecordData();
            if(event.getStatus() == 2 && recordData == null){
                handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_HAS_BEEN_KILLED);
                //清理事件
                userData.setEvent(new DouLuoDaLuUserEvent());
                return handleResult;
            }
            if(event != context.getUserData().getEvent()){
                handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_HAS_BEEN_KILLED);
                //清理事件
                userData.setEvent(new DouLuoDaLuUserEvent());
                return handleResult;
            }
            //重新掉落该区域
            if(enemyUserData.getRegionId() == context.getUserData().getRegionId() && (enemyUserData.getEntryRegionTime() > 0 && event.getAddTime() < enemyUserData.getEntryRegionTime())){
                handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_HAS_BEEN_KILLED);
                //清理事件
                userData.setEvent(new DouLuoDaLuUserEvent());
                return handleResult;
            }
            String contextUnionUid = context.getUnionUid();
            String enemyUnionUid = CrossDouLuoDaLuMgr.getUserActivityUnionUid(enemyUserData.getActivityId(), enemyUserData.getUserId());
            if(enemyUnionUid.equals(contextUnionUid)
                    && !StringUtils.isNullOrEmpty(contextUnionUid)){
                handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_NOT_ATTACK_UNION_MEMBER);
                //清理事件
                userData.setEvent(new DouLuoDaLuUserEvent());
                return handleResult;
            }
            //对手区域变更
            //无法再降区，不可能还可以被打
            if(enemyUserData.getRegionId() != context.getUserData().getRegionId() || preRegionInfo == null){
                handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_PLAYER_NOT_IN_REGION);
                //清理事件
                userData.setEvent(new DouLuoDaLuUserEvent());
                return handleResult;
            }

            if(event.getStatus() == 0){
                event.setStatus(1);
            }

            totalBlood = enemyUserData.getTotalBlood();

            long attackHunLi = CrossDouLuoDaLuMgr.getHunLiDamageAddBuff(context, userData);
            context.getActivity().attackDamage(attackHunLi, enemyUserData.getBlood(), handleResult);

            if(handleResult.isKill()){
                //计算对方损失的魂环
                enemyLost = CrossDouLuoDaLuMgr.calBattleReward(hunHuanProperty, goodsProperty, context, regionInfo, eventInfo, enemyUserData);

                //处理降区域
                preRegionInfo = CrossDouLuoDaLuMgr.dropRegionInfo(context.getActivity(), enemyUserData);

                //击败提示（给被击败者）
                CrossDouLuoDaLuMgr.pushEnemyTip(context, handleResult, enemyUserData, hunHuanProperty, enemyLost, 1);

                //对手的被击败次数
                enemyUserData.getEnemyInfoMap().put(userData.getUserId(), enemyUserData.getEnemyInfoMap().getOrDefault(userData.getUserId(), 0) + 1);

                markEnemySet = enemyUserData.getCanAttackUserSet();
                enemyUserData.setCanAttackUserSet(new ConcurrentHashSet<>());
                //清理事件
                userData.setEvent(new DouLuoDaLuUserEvent());
            }else {
                event.setAttackTime(attackTime);
                event.setBlood(handleResult.getBlood());
                enemyUserData.setBlood(handleResult.getBlood());
                markEnemySet = enemyUserData.getCanAttackUserSet();
            }

            //更新我的协助记录
            helpRecordData = userData.getCurrentHelpRecordData();
            if(helpRecordData != null && helpRecordData.getTargetId() == enemyUserData.getUserId()) {
                helpRecordData.setTargetBlood(handleResult.getBlood());
                if (handleResult.isKill()) {
                    CrossDouLuoDaLuMgr.updateHelpDataKillInfo(helpRecordData, userData.getUserId(), now , userData);
                }
                CrossDouLuoDaLuMgr.updateAttackInfo(context.getUserData(), helpRecordData, handleResult.getDamage(), attackTime);
            }


            if(handleResult.isKill()){
                context.getActivity().removeAreaUser(oldRegionId, enemyUserData.getUserId());
                context.getActivity().addAreaUser(preRegionInfo.getRegionId(), enemyUserData);
            }

            //奖励处理
            dealAttackReward(handleResult, context, totalBlood, hunHuanProperty, goodsProperty);

            //对手的防守日志
            CrossDouLuoDaLuMgr.notifyUserBeFight(userData, enemyUserData, handleResult.getDamage(), handleResult.getBlood(), event.getStatus() == 2 ? 2 : 1,
                    enemyLost ? handleResult.getHunHuan() : null);

            //森林事件日志
            if(eventInfo.isShowLog() && CrossDouLuoDaLuMgr.containHunHuan(hunHuanProperty, 10000)) {
                DouLuoDaLuEventNoticeData noticeData = context.getActivity().addEventNotice(context.getUserData(), eventInfo, event.getMonsterId(),
                        handleResult.getHunHuan(), "", null, enemyUserData, 1, null);
                context.getActivity().syncDouLuoDaLuEventNotice(noticeData);
            }

            //攻击事件广播
            CrossDouLuoDaLuMgr.handleAttackPlayerEventBroadcast(handleResult, context, markEnemySet, enemyUserData, attackTime);

            if(handleResult.isKill()){
                //击杀日志
                CrossAutoLogMgr.add(new LogDouLuoDaLuKill(context.getActivityId(), context.getUserId(), context.getUserData().getRegionId(),
                        2, event.getEnemyUserId(), handleResult.getDamage(), helpRecordData == null ? 0 : context.getUserId(), helpRecordData == null ? 0 : helpRecordData.getRecordTime(), event.getAddTime(), DateHelper.getCurrentSecond()));

                //魂环日志
                CrossAutoLogMgr.add(new LogDouLuoDaLuHunHuan(context.getActivityId(), context.getUserId(), 1, event.getRegionId(), PropertyHelper.parsePropertyToString(hunHuanProperty),
                        LogDouLuoDaLuHunHuan.getReason(2, enemyLost), event.getEnemyUserId()));

                CrossAutoLogMgr.add(new LogDouLuoDaLuHunHuan(context.getActivityId(), enemyUserData.getUserId(), 0, event.getRegionId(), PropertyHelper.parsePropertyToString(hunHuanProperty),
                        LogDouLuoDaLuHunHuan.getReason(3, enemyLost), context.getUserId()));
            }

        }else if(action == 2){
            //可标识

            if(event != context.getUserData().getEvent() || event.getRegionId() != context.getUserData().getRegionId()){
                handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_PLAYER_NOT_IN_REGION);
                userData.setEvent(new DouLuoDaLuUserEvent());
                return handleResult;
            }

            //标记玩家
            DouLuoDaLuHelpRecordData oldMark = userData.getCurrentHelpRecordData();

            DouLuoDaLuHelpRecordData newMark;


            Map<Long, DouLuoDaLuHelpRecordData> map = context.getActivity().getHelpRecordDataMap(context.getTeamData());
            if(enemyUserData.getRegionId() != context.getUserData().getRegionId()){
                handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_PLAYER_NOT_IN_REGION);
                userData.setEvent(new DouLuoDaLuUserEvent());
                return handleResult;
            }
            for (Map.Entry<Long, DouLuoDaLuHelpRecordData> dataEntry : map.entrySet()) {
                if(dataEntry.getValue().getTargetId() == enemyUserData.getUserId()){
                    handleResult.setRet(GameErrorCode.E_DOU_LUO_DA_LU_MARK_TARGET_HAD_IN_LIST);
                    return handleResult;
                }
            }
            newMark = buildHelpRecordData(event, enemyUserData.getRegionId(), enemyUserData.getTotalBlood(), enemyUserData.getBlood(), enemyUserData.getUserId(), event.getAddTime());
            userData.setCurrentHelpRecordData(newMark);


            replaceHelpRecord(userData, oldMark, newMark);

            CrossDouLuoDaLuMgr.updateAttackInfo(context.getUserData(), newMark, event.getTotalBlood() - event.getBlood(), event.getAttackTime());

            event.setStatus(2);
            userData.setUpdateOption();

            //context.getActivity().broadcastHelpRecordAttackInfo(context.getTeamData());
            context.getActivity().checkUserRedHot(userData, context.getTeamData());
        }else if(action == 3){
            //绕过
            if(userData.getEvent().getStatus() != 2){

                enemyUserData.getCanAttackUserSet().remove(userData);

            }
            //清除事件
            userData.setEvent(new DouLuoDaLuUserEvent());
        }
        handleResult.setEventId(eventInfo.getEventId());
        return handleResult;
    }

}
